<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>

</head>
<body oncontextmenu=self.event.returnValue=false onselectstart="return false">

  <canvas id="domId" width="800" height="800" style="border: solid">

  </canvas>
  <br/>
  <button onclick="addWall()">添加墙</button>
  <button onclick="setStart()">设置起点</button>
  <button onclick="setEnd()">设置终点</button>
  <button onclick="findPath()">计算路径</button>
  <button onclick="clearAll()">清空</button>

</body>

<script src="../dist/A_Star.js"></script>
<script>

  let task = new AStar.Task();

  let dom = document.getElementById('domId');
  let ctx = dom.getContext('2d');
  let cubeWidth = 10;

  let model = '';

  function addWall(){
    model = 'addWall';
  }
  function setStart(){
    model = 'setStart';
  }
  function setEnd(){
    model = 'setEnd';
  }
  function findPath(){
    task.findPath();
    ctx.fillStyle = '#ff0000';
    for(let i=0; i<task.pathSet.length-1; i++){
      ctx.fillRect(task.pathSet[i].x*cubeWidth, task.pathSet[i].y*cubeWidth, cubeWidth, cubeWidth);
    }
  }
  function clearAll(){
    task.reSet();
    ctx.clearRect(0,0,800,800);
  }

  dom.addEventListener('mousemove', function (e) {
    if(e.buttons === 0 || model !== 'addWall'){
      return;
    }
    let x = Math.floor(e.offsetX/cubeWidth);
    let y = Math.floor(e.offsetY/cubeWidth);

    task.addWall(x, y);
    ctx.fillStyle = '#000000';
    ctx.fillRect(x*cubeWidth, y*cubeWidth, cubeWidth, cubeWidth);
  });

  dom.addEventListener('click', function (e) {
    let x = Math.floor(e.offsetX/cubeWidth);
    let y = Math.floor(e.offsetY/cubeWidth);
    if(model === 'addWall'){
      task.addWall(x, y);

      ctx.fillStyle = '#000000';
      ctx.fillRect(x*cubeWidth, y*cubeWidth, cubeWidth, cubeWidth);
    }else if(model === 'setStart'){
      if(task.startNode){
        clearOne(task.startNode.x, task.startNode.y);
      }
      task.setStart(x, y);
      ctx.fillStyle = '#00ff00';
      ctx.fillRect(x*cubeWidth, y*cubeWidth, cubeWidth, cubeWidth);
    }else if(model === 'setEnd'){
      if(task.endNode){
        clearOne(task.endNode.x, task.endNode.y);
      }
      task.setEnd(x, y);
      ctx.fillStyle = '#0000ff';
      ctx.fillRect(x*cubeWidth, y*cubeWidth, cubeWidth, cubeWidth);
    }
  });

  function clearOne(x, y){
    ctx.clearRect(x*cubeWidth, y*cubeWidth, cubeWidth, cubeWidth);
  }

</script>

</html>
